<template>
  <div id="addJournal">
    <el-form :model="formData"
             :rules="rules"
             ref="ruleForm"
             label-width="100px">
      <el-form-item label="姓名"
                    prop="user">
        <el-input v-model="formData.user"
                  size="small"></el-input>
      </el-form-item>
      <el-form-item label="内容"
                    prop="content">
        <el-input type="textarea"
                  v-model="formData.content"></el-input>
      </el-form-item>
      <el-form-item label="摘要"
                    prop="summary">
        <el-input v-model="formData.summary"
                  size="small"></el-input>
      </el-form-item>
      <el-form-item label="日期"
                    prop="date">
        <el-date-picker v-model="formData.date"
                        type="date"
                        placeholder="选择日期"
                        value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="hanldeSumbmit('ruleForm')">提交</el-button>
        <el-button @click="hanldeCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  props: {
    value: Object,
    action: String
  },
  data: function () {
    return {
      formData: this.initModel(),
      addFormName: null,
      rules: {
        user: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        summary: [
          { required: true, message: '请输入摘要', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    // 初始化赋值，点击修改获取到的model，赋值给formData。
    this.$nextTick(() => {
      if (this.value) {
        this.formData = this.value
      }
    })
  },
  methods: {
    initModel: function () {
      return {
        user: '',
        content: '',
        date: '',
        summary: ''
      }
    },
    // 提交
    hanldeSumbmit: function (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$store.dispatch(this.action, this.formData)
            .then(res => {
              this.$emit('dialog:close')
            })
        }
      })
    },
    // 取消，关闭对话框
    hanldeCancel: function () {
      // 事件传到父组件GDialog.vue中
      // 如果是点击编辑打开的这个对话框，就回收相应的资源，并且清空数据，判断条件就是看value是否有数据
      if (this.value) {
        this.$emit('dialog:close')
      } else {
        this.$emit('dialog:hide')
      }
    }
  },
  watch: {
    // 监测value是否有变化，如果有，就将model赋值给formData
    value: function () {
      this.formData = this.value
    }
  }
}
</script>
<style>
#addJournal .el-input,
.el-textarea {
  width: 500px;
}
</style>
